//
//  CRegisterView.m
//  HCHK_iphone
//
//  Created by yilong zhang on 11-12-31.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CRegisterView.h"

//=======================================================================================================================

@implementation CPosition

@synthesize m_City;
@synthesize m_JDu;
@synthesize m_WDu;

-(void)dealloc
{
    [m_City release];
    [m_JDu release];
    [m_WDu release];
    
    [super dealloc];
}

@end

//=======================================================================================================================

@implementation CCity

@synthesize m_Section;
@synthesize m_Rows;

-(id)init
{
    self = [super init];
    if (self)
    {
        self.m_Rows = [NSMutableArray array];
    }
    
    return self;
}

-(void)dealloc
{
    [m_Section release];
    [m_Rows release];
    
    [super dealloc];
}

@end

//=======================================================================================================================

@implementation CRegisterView

@synthesize m_Icon;
@synthesize m_IconBtn;
@synthesize m_Name;
@synthesize m_Pwd;
@synthesize m_Nick;
@synthesize m_Mail;
@synthesize m_City;
@synthesize m_Citytf;
@synthesize m_Panel;
@synthesize m_PanelCenter;
@synthesize m_CommitBtn;
@synthesize m_OldCounter;

//imagepicker
@synthesize m_Sheet;
@synthesize m_PhotoCtrl;
@synthesize m_CamareCtrl;

//city
@synthesize m_CityTable;
@synthesize m_Cities;
@synthesize m_PositionsNum;
@synthesize m_Positions;
@synthesize m_AddInfo;

//action
@synthesize m_Target;
@synthesize m_Action;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        // Initialization code
        //self.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
        UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        bg.image = [UIImage imageNamed:@"appbg.jpg"];
        [self addSubview:bg];
        [bg release];
        
        self.m_Title = @"加入好吃客";
        
        UIView *shadow = [[UIView alloc] initWithFrame:CGRectMake(5, 15, 70, 70)];
        shadow.layer.cornerRadius = 35;
        shadow.layer.shadowOffset = CGSizeMake(2, 2);
        shadow.layer.shadowOpacity= 0.8;
        shadow.layer.shadowColor  = [[UIColor blackColor] CGColor];
        shadow.backgroundColor = [UIColor blackColor];
        [self addSubview:shadow];
        [shadow release];
        
        m_Icon = [[UIImageView alloc] initWithFrame:CGRectMake(5, 15, 70, 70)];
        m_Icon.image = [UIImage imageNamed:@"dicon.png"];
        m_Icon.layer.masksToBounds = YES;
        m_Icon.layer.cornerRadius  = 35;
        [self addSubview:m_Icon];
        [m_Icon release];
        
        m_IconBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        m_IconBtn.frame = m_Icon.frame;
        m_IconBtn.alpha = 0.1;
        [m_IconBtn addTarget:self action:@selector(DidChangeIconBtnDown:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:m_IconBtn];
        
        bg = [[UIImageView alloc] initWithFrame:CGRectMake(84, 0, 237, 184)];
        bg.image = [UIImage imageNamed:@"regline.png"];
        [self addSubview:bg];
        [bg release];
        
        m_Panel = [[UIView alloc] initWithFrame:CGRectMake(84, 24, 233, 130)];
        m_Panel.backgroundColor = [UIColor clearColor];
        //m_Panel.backgroundColor = [UIColor whiteColor];
        //m_Panel.layer.cornerRadius = 10;
        //m_Panel.layer.borderColor  = [[UIColor lightGrayColor] CGColor];
        //m_Panel.layer.borderWidth  = 1;
        [self addSubview:m_Panel];
        [m_Panel release];
        //m_PanelCenter = CGPointMake(m_Panel.center.x, m_Panel.center.y);
        
        bg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 2, 213, 30)];
        bg.image = [UIImage imageNamed:@"regnick.png"];
        [m_Panel addSubview:bg];
        [bg release];
        
        m_Nick = [[UITextField alloc] initWithFrame:CGRectMake(55, 4, 167, 30)];
        //m_Nick.placeholder = @"昵称";
        m_Nick.font = [UIFont systemFontOfSize:15];
        m_Nick.delegate = self;
        m_Nick.returnKeyType = UIReturnKeyDone;
        [m_Nick addTarget:self action:@selector(DidTextFieldChanged:) forControlEvents:UIControlEventEditingChanged];
        m_Nick.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        [m_Panel addSubview:m_Nick];
        [m_Nick release];
        
        /*m_Name = [[UITextField alloc] initWithFrame:CGRectMake(55, 2, 167, 30)];
        m_Name.placeholder = @"用户名";
        m_Name.font = [UIFont systemFontOfSize:15];
        m_Name.delegate = self;
        m_Name.returnKeyType = UIReturnKeyDone;
        [m_Name addTarget:self action:@selector(DidTextFieldChanged:) forControlEvents:UIControlEventEditingChanged];
        m_Name.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        [m_Panel addSubview:m_Name];
        [m_Name release];
        
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 40, m_Panel.frame.size.width, 1)];
        line.image = [UIImage imageNamed:@"line.png"];
        line.alpha = 0.5;
        [m_Panel addSubview:line];
        [line release];*/
        
        bg = [[UIImageView alloc] initWithFrame:CGRectMake(10, bg.frame.origin.y+bg.frame.size.height+16, 213, 30)];
        bg.image = [UIImage imageNamed:@"regemail.png"];
        [m_Panel addSubview:bg];
        [bg release];
        
        m_Mail = [[UITextField alloc] initWithFrame:CGRectMake(55, bg.frame.origin.y+2, 167, 30)];
        //m_Mail.placeholder = @"电子邮件";
        m_Mail.font = [UIFont systemFontOfSize:15];
        m_Mail.delegate = self;
        m_Mail.keyboardType = UIKeyboardTypeEmailAddress;
        m_Mail.returnKeyType = UIReturnKeyDone;
        [m_Mail addTarget:self action:@selector(DidTextFieldChanged:) forControlEvents:UIControlEventEditingChanged];
        m_Mail.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        [m_Panel addSubview:m_Mail];
        [m_Mail release];
        
        bg = [[UIImageView alloc] initWithFrame:CGRectMake(10, bg.frame.origin.y+bg.frame.size.height+16, 213, 30)];
        bg.image = [UIImage imageNamed:@"regpwd.png"];
        [m_Panel addSubview:bg];
        [bg release];
        
        m_Pwd = [[UITextField alloc] initWithFrame:CGRectMake(55, bg.frame.origin.y+2, 167, 30)];
        //m_Pwd.placeholder = @"密码";
        m_Pwd.font = [UIFont systemFontOfSize:15];
        m_Pwd.secureTextEntry = YES;
        m_Pwd.delegate = self;
        m_Pwd.returnKeyType = UIReturnKeyDone;
        [m_Pwd addTarget:self action:@selector(DidTextFieldChanged:) forControlEvents:UIControlEventEditingChanged];
        m_Pwd.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        [m_Panel addSubview:m_Pwd];
        [m_Pwd release];
        
        /*line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 80, m_Panel.frame.size.width, 1)];
        line.image = [UIImage imageNamed:@"line.png"];
        line.alpha = 0.5;
        [m_Panel addSubview:line];
        [line release];
        
        m_Nick = [[UITextField alloc] initWithFrame:CGRectMake(10, 80, m_Panel.frame.size.width-20, 40)];
        m_Nick.placeholder = @"昵称";
        m_Nick.font = [UIFont systemFontOfSize:15];
        m_Nick.delegate = self;
        m_Nick.returnKeyType = UIReturnKeyDone;
        [m_Nick addTarget:self action:@selector(DidTextFieldChanged:) forControlEvents:UIControlEventEditingChanged];
        m_Nick.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        [m_Panel addSubview:m_Nick];
        [m_Nick release];
        
        line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 120, m_Panel.frame.size.width, 1)];
        line.image = [UIImage imageNamed:@"line.png"];
        line.alpha = 0.5;
        [m_Panel addSubview:line];
        [line release];
        
        line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 160, m_Panel.frame.size.width, 1)];
        line.image = [UIImage imageNamed:@"line.png"];
        line.alpha = 0.5;
        [m_Panel addSubview:line];
        [line release];
        
        m_Citytf = [[UITextField alloc] initWithFrame:CGRectMake(10, 160, m_Panel.frame.size.width-20, 40)];
        m_Citytf.placeholder = @"我所在的城市";
        m_Citytf.font = [UIFont systemFontOfSize:15];
        m_Citytf.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        [m_Panel addSubview:m_Citytf];
        [m_Citytf release];
        
        m_City = [UIButton buttonWithType:UIButtonTypeCustom];
        m_City.alpha = 0.1;
        m_City.frame = m_Citytf.frame;
        [m_City addTarget:self action:@selector(DidCityBtnDown:) forControlEvents:UIControlEventTouchUpInside];
        [m_Panel addSubview:m_City];
        
        m_CommitBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        m_CommitBtn.frame = CGRectMake(20, m_Panel.frame.size.height+m_Panel.frame.origin.y+10, m_Panel.frame.size.width, 30);
        [m_CommitBtn setTitle:@"创建新账号" forState:UIControlStateNormal];
        [m_CommitBtn addTarget:self action:@selector(DidCommitBntDown:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:m_CommitBtn];
        
        m_OldCounter = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        m_OldCounter.frame = CGRectMake(20, m_CommitBtn.frame.origin.y+m_CommitBtn.frame.size.height+10, m_Panel.frame.size.width, 30);

        [m_OldCounter setTitle:@"我已经有账号了!" forState:UIControlStateNormal];
        [m_OldCounter addTarget:self action:@selector(DidOldCounterBtnDown:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:m_OldCounter];*/
    }
    
    return self;
}

-(void)dealloc
{
    [m_Positions release];
    
    [super dealloc];
}

//imagepicker
-(void)ShowPickerView
{
    if (!m_Sheet)
    {
        m_Sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"相册", @"拍照", nil];
        m_Sheet.actionSheetStyle = UIBarStyleBlackTranslucent;
        [m_Sheet showInView:[CRootCtrlManager DefaultRootCtrl].view];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //0-CANCEL
    //1-ALBUM
    //2-CAMERA
    [self DidPickerViewBtnDown:buttonIndex];
}

-(void)DidPickerViewBtnDown:(int)sender
{
    //photo
    if (1 == sender)
    {
        m_PhotoCtrl = [[PhotosViewController alloc] initWithSize:CGSizeMake(320, 320)];
        m_PhotoCtrl.m_delegate = self;
        m_PhotoCtrl.m_Target = self;
        m_PhotoCtrl.m_Action = @selector(DidPhotograph:);
        [[CRootCtrlManager DefaultRootCtrl] presentModalViewController:m_PhotoCtrl animated:YES];
        [m_PhotoCtrl release];
    }
    //camare
    else if (2 == sender)
    {
        if ([CameraViewController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            m_CamareCtrl = [[CameraViewController alloc] initWithSize:CGSizeMake(320, 320)];
            m_CamareCtrl.m_delegate = self;
            m_CamareCtrl.m_Target = self;
            m_CamareCtrl.m_Action = @selector(DidPhotograph:);
            [[CRootCtrlManager DefaultRootCtrl] presentModalViewController:m_CamareCtrl animated:YES];
            [m_CamareCtrl release];
        }
        else 
        {
            UIAlertView *nocamera = [[UIAlertView alloc] initWithTitle:@"提示" message:@"抱歉，该设备不支持拍照功能。" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
            [nocamera show];
            [nocamera autorelease];
        }
    }
    //cancel
    else
    {;}
    
    [m_Sheet release];
    m_Sheet = nil;
}

-(void)ImagePickerDidSelectImage:(UIImage *)image
{
    if (image)
    {
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        m_Icon.image = [UIImage imageWithData:data];
    }
}

-(void)CImagePickerDidSelectImage:(UIImage *)image
{
    if (image)
    {
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        m_Icon.image = [UIImage imageWithData:data];
    }
}

-(void)DidPhotograph:(UIImage*)image
{
    /*if (image)
    {
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        m_Icon.image = [UIImage imageWithData:data];
    }*/
}

-(void)DidChangeIconBtnDown:(UIButton*)sender
{
    [self ShowPickerView];
}

-(void)DidCityBtnDown:(UIButton*)sender
{
    [self HiddenKeyBoard];
    
    //[self ShowCityPicker];

    //保存当前等位信息
    m_AddInfo = [[CAddrInfo alloc] init];
    m_AddInfo.m_strCity     = [NSString stringWithFormat:@"%@", [CLocator DefaultLocator].m_AddrInfo.m_strCity];
    m_AddInfo.m_strProvince = [NSString stringWithFormat:@"%@", [CLocator DefaultLocator].m_AddrInfo.m_strProvince];
    m_AddInfo.m_strCountry  = [NSString stringWithFormat:@"%@", [CLocator DefaultLocator].m_AddrInfo.m_strCountry];
    m_AddInfo.m_strSum      = [NSString stringWithFormat:@"%@", [CLocator DefaultLocator].m_AddrInfo.m_strSum];
    m_AddInfo.m_fX          = [CLocator DefaultLocator].m_AddrInfo.m_fX;
    m_AddInfo.m_fY          = [CLocator DefaultLocator].m_AddrInfo.m_fY;
    
    CRootCtrlManager *root = [CRootCtrlManager DefaultRootCtrl];
    CCitySelector *citysel = [[CCitySelector alloc] initWithFrame:CGRectMake(0, 0, root.view.frame.size.width, root.view.frame.size.height) ShowGrade:ToCity];
    citysel.delegate = self;
    //citysel.m_Title.text = @"我所在的城市";
    //citysel.m_Title.font = [UIFont boldSystemFontOfSize:18];
    //citysel.m_NaviItem.leftBarButtonItem = nil;
    [root.view addSubview:citysel];
    [citysel release];
}

-(void)DidCitySelectorActived:(int)index Object:(id)object
{
    CCitySelector *cityself = object;
    if ([cityself.m_City.text length] > 6)
    {
        NSString *substring = [[NSString alloc] initWithFormat:@"%@", [cityself.m_City.text substringFromIndex:6]];
        NSArray *arr = [substring componentsSeparatedByString:@" "];
        m_Citytf.text = [arr objectAtIndex:[arr count]-1];
        [substring release];
    }
        
    [cityself removeFromSuperview];
    
    //还原定位信息
    [CLocator DefaultLocator].m_AddrInfo.m_strCity      = [NSString stringWithFormat:@"%@",self.m_AddInfo.m_strCity];
    [CLocator DefaultLocator].m_AddrInfo.m_strProvince  = [NSString stringWithFormat:@"%@",self.m_AddInfo.m_strProvince];
    [CLocator DefaultLocator].m_AddrInfo.m_strCountry   = [NSString stringWithFormat:@"%@",self.m_AddInfo.m_strCountry];
    [CLocator DefaultLocator].m_AddrInfo.m_strSum       = [NSString stringWithFormat:@"%@",self.m_AddInfo.m_strSum];
    [CLocator DefaultLocator].m_AddrInfo.m_fY           = self.m_AddInfo.m_fY;
    [CLocator DefaultLocator].m_AddrInfo.m_fX           = self.m_AddInfo.m_fX;
    [CLocator DefaultLocator].m_Coordinate2D = CLLocationCoordinate2DMake([CLocator DefaultLocator].m_AddrInfo.m_fX, [CLocator DefaultLocator].m_AddrInfo.m_fY);
    
    [m_AddInfo release];
}

-(void)DidCommitBntDown:(UIButton*)sender
{
    //密码大写转小写
    m_Pwd.text = [m_Pwd.text lowercaseString];
    [m_Target performSelector:m_Action withObject:self];
}

-(void)DidOldCounterBtnDown:(UIButton*)sender
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.tag = 1;
    [[CUserPageCtrl DefaultUserPage] OnTopBarBackBtnDown:btn];
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    /*[UIView beginAnimations:nil context:nil];
    m_Panel.center = CGPointMake(m_PanelCenter.x, 100);
    [UIView commitAnimations];*/
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self HiddenKeyBoard];
    
    return YES;
}

-(void)DidTextFieldChanged:(UITextField*)textfield
{
    //name
    if (m_Name == textfield)
    {
        [m_Name IsNameRightFormat:10];
    }
    //pwd
    else if (m_Pwd == textfield)
    {
        [m_Pwd IsPwdRightFormat:18];
    }
    //nick
    else if (m_Nick == textfield)
    {
        [m_Nick IsNickRightFormat:12];
    }
    else {;}
}

-(void)HiddenKeyBoard
{
    [m_Name resignFirstResponder];
    [m_Pwd resignFirstResponder];
    [m_Nick resignFirstResponder];
    [m_Mail resignFirstResponder];
    
    /*[UIView beginAnimations:nil context:nil];
    m_Panel.center = CGPointMake(m_PanelCenter.x, m_PanelCenter.y);
    [UIView commitAnimations];*/
}

//city
-(void)InitCityPicker
{
    m_Positions = [[NSMutableArray array] retain];
    m_Cities = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"citys" ofType:@"txt"]];
    
    NSArray             *keys     = [m_Cities allKeys];
    NSArray             *infos    = nil;
    NSArray             *info     = nil;
    
    CCity        *city     = nil;
    CPosition    *position = nil;
    
    m_PositionsNum = [keys count];
    
    for (int i=0; i<m_PositionsNum; i++)
    {
        infos = [m_Cities objectForKey:[keys objectAtIndex:i]];
        city  = [[CCity alloc] init];
        city.m_Section = [keys objectAtIndex:i];
        for (int j=0; j<[infos count]; j++)
        {
            info = [infos objectAtIndex:j];
            position = [[CPosition alloc] init];
            position.m_City = [info objectAtIndex:0];
            position.m_JDu  = [info objectAtIndex:1];
            position.m_WDu  = [info objectAtIndex:2];
            [city.m_Rows addObject:position];
            [position release];
        }
        [m_Positions addObject:city];
        [city release];
    }
    
    m_CityTable = [[UITableView alloc] initWithFrame:CGRectMake(self.frame.size.width, 0, self.frame.size.width, self.frame.size.height) style:UITableViewStyleGrouped];
    m_CityTable.dataSource = self;
    m_CityTable.delegate   = self;
    m_CityTable.backgroundColor = self.backgroundColor;
    [self addSubview:m_CityTable];
    [m_CityTable release];
}

-(void)ShowCityPicker
{
    //[CUserPageCtrl DefaultUserPage].m_RetBtn.hidden = YES;
    
    [UIView beginAnimations:nil context:nil];
    m_CityTable.center = CGPointMake(m_CityTable.center.x-m_CityTable.frame.size.width, m_CityTable.center.y);
    [UIView commitAnimations];
}

-(void)HiddenCityPicker
{
    [UIView beginAnimations:nil context:nil];
    m_CityTable.center = CGPointMake(m_CityTable.center.x+m_CityTable.frame.size.width, m_CityTable.center.y);
    [UIView commitAnimations];
    
    //[CUserPageCtrl DefaultUserPage].m_RetBtn.hidden = NO;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CCity *city = [m_Positions objectAtIndex:section];
    
    return [city.m_Rows count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCellStyle style = UITableViewCellStyleValue1;
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BaseCell"];
	
	if (nil == cell)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"BaseCell"] autorelease];
    }
    
    CCity     *city    = [m_Positions objectAtIndex:indexPath.section];
    CPosition *position= [city.m_Rows objectAtIndex:indexPath.row];
    NSString  *info    = [NSString stringWithFormat:@"%@ (%@, %@)", position.m_City, position.m_JDu, position.m_WDu];
    
    cell.textLabel.text = info;
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return m_PositionsNum;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    CCity *city = [m_Positions objectAtIndex:section];
    
    return city.m_Section;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CCity *city = [m_Positions objectAtIndex:indexPath.section];
    CPosition *position = [city.m_Rows objectAtIndex:indexPath.row];
    m_Citytf.text = [NSString stringWithFormat:@"%@", position.m_City];
    
    [self HiddenCityPicker];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
